package com.jt.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy {

    //传入target目标对象获取代理对象的
    //利用代理对象 实现方法的扩展
    public static Object getProxy(Object target){
        //1.获取类加载器
        ClassLoader classLoader = target.getClass().getClassLoader();
        //2.获取接口数组类型
        Class[] interfaces = target.getClass().getInterfaces();
        //3.代理对象执行方法时的回调方法(代理对象调用方法时,执行InvocationHandler)
        return Proxy.newProxyInstance(classLoader,interfaces,invocationHandler(target));
    }

    //要求必须传递目标对象
    public static InvocationHandler invocationHandler(Object target){
       return new InvocationHandler() {
           @Override
           public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
               System.out.println("事务开启");
               //获取目标方法的返回值
               Object result = method.invoke(target,args);
               System.out.println("事务提交");
               return result;
           }
       };
    }

    public static Object getTimePorxy(Object target){
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class[] interfaces = target.getClass().getInterfaces();
        return Proxy.newProxyInstance(classLoader,interfaces,invocationHandlerTime(target));
    }

    //要求必须传递目标对象
    public static InvocationHandler invocationHandlerTime(Object target){
        return new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //开始时间
                long startTime = System.currentTimeMillis();
                //让目标方法执行 结果
                Object result = method.invoke(target,args);
                long endTime = System.currentTimeMillis();
                System.out.println("耗时:"+(endTime - startTime));
                return result;
            }
        };
    }

}
